// content.js  为浏览器添加扩展功能
if (!window.GLOBAL_PARTICLE_EFFECT) {
    window.GLOBAL_PARTICLE_EFFECT = (function() {
        // =============== 核心配置 ================
        const CONFIG = {
            PARTICLE_COUNT: 50,          // 粒子数量(原版99)
            LINE_MAX_DISTANCE: 6000,     // 连线距离平方阈值
            MOUSE_INFLUENCE: 0.03,       // 鼠标影响系数
            GATHER_FORCE: 0.03,          // 聚拢力度（原版0.03）
            GATHER_THRESHOLD: 0.5,       // 触发聚拢的距离比例（max/2）
            MOUSE_MAX_DISTANCE: 10000,   // 鼠标作用范围平方（原版2e4）
            Z_INDEX: -1,                 // 画布层级
            OPACITY: 0.75                // 透明度
        };

        // =============== 核心逻辑 ================
        let canvas, ctx;
        let particles = [];
        let mouse = { x: null, y: null, max: CONFIG.MOUSE_MAX_DISTANCE };
        let animationFrameId;
        let width, height;

        // HSL转RGB（原版保留）
        function hslToRgb(h, s, l) {
            h = (h % 360 + 360) % 360 / 360;
            s = Math.min(100, Math.max(0, s)) / 100;
            l = Math.min(100, Math.max(0, l)) / 100;

            let r, g, b;
            if (0 === s) {
                r = g = b = l;
            } else {
                const hue2rgb = (p, q, t) => {
                    if(t < 0) t += 1;
                    if(t > 1) t -= 1;
                    return t < 1/6 ? p + (q - p) * 6 * t :
                        t < 1/2 ? q :
                            t < 2/3 ? p + (q - p) * (2/3 - t) * 6 : p;
                };
                const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
                const p = 2 * l - q;
                r = Math.round(hue2rgb(p, q, h + 1/3) * 255);
                g = Math.round(hue2rgb(p, q, h) * 255);
                b = Math.round(hue2rgb(p, q, h - 1/3) * 255);
            }
            return [
                Math.min(255, Math.max(0, r)),
                Math.min(255, Math.max(0, g)),
                Math.min(255, Math.max(0, b))];
        }

        // 动态颜色（原逻辑）
        function getCurrentColor() {
            const date = new Date();
            const totalMinutes = date.getHours() * 60 + date.getMinutes();
            return hslToRgb((totalMinutes * 0.25) % 360, 100, 50);
        }

        // 初始化画布
        function initCanvas() {
            const oldCanvas = document.querySelector('canvas[c_n]');
            if (oldCanvas) oldCanvas.remove();

            canvas = document.createElement('canvas');
            canvas.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                z-index: ${CONFIG.Z_INDEX};
                opacity: ${CONFIG.OPACITY};
                pointer-events: none;
            `;
            document.body.appendChild(canvas);
            ctx = canvas.getContext('2d');
            updateSize();
        }

        // 更新尺寸
        function updateSize() {
            width = canvas.width = window.innerWidth;
            height = canvas.height = window.innerHeight;
        }

        // 创建粒子（原初始化逻辑）
        function createParticles() {
            particles = Array.from({ length: CONFIG.PARTICLE_COUNT }, () => ({
                x: Math.random() * width,
                y: Math.random() * height,
                xa: (Math.random() * 2 - 1),
                ya: (Math.random() * 2 - 1),
                max: CONFIG.LINE_MAX_DISTANCE
            }));
        }

        // 核心动画循环（整合聚拢效果）
        function animate() {
            ctx.clearRect(0, 0, width, height);
            
            const color = getCurrentColor();
            const lineColor = `rgba(${color[0]},${color[1]},${color[2]}`;
            const dotColor = `rgb(${color[0]},${color[1]},${color[2]})`;

            ctx.fillStyle = dotColor;
            const checkArray = [mouse, ...particles];

            particles.forEach(particle => {
                // 更新位置
                particle.x += particle.xa;
                particle.y += particle.ya;
                
                // 边界反弹
                if (particle.x < 0 || particle.x > width) particle.xa *= -1;
                if (particle.y < 0 || particle.y > height) particle.ya *= -1;

                // 绘制粒子
                ctx.fillRect(particle.x - 0.5, particle.y - 0.5, 1, 1);

                // 聚拢效果检测
                checkArray.forEach(target => {
                    if (target !== mouse) return;
                    
                    const dx = particle.x - target.x;
                    const dy = particle.y - target.y;
                    const distSq = dx*dx + dy*dy;

                    // 原版聚拢条件
                    if (distSq > target.max * CONFIG.GATHER_THRESHOLD) {
                        particle.x -= dx * CONFIG.GATHER_FORCE;
                        particle.y -= dy * CONFIG.GATHER_FORCE;
                    }
                });

                // 连线检测
                checkArray.forEach(target => {
                    if (particle === target) return;
                    
                    const dx = particle.x - target.x;
                    const dy = particle.y - target.y;
                    const distSq = dx*dx + dy*dy;

                    if (distSq < target.max) {
                        const alpha = (target.max - distSq)/target.max;
                        ctx.beginPath();
                        
                        // 鼠标连线特殊处理
                        if (target === mouse) {
                            ctx.strokeStyle = `${lineColor},${Math.min(1, alpha + 0.4)})`;
                            ctx.lineWidth = alpha;
                        } else {
                            ctx.strokeStyle = `${lineColor},${Math.min(1, alpha + 0.2)})`;
                            ctx.lineWidth = alpha/2;
                        }
                        
                        ctx.moveTo(particle.x, particle.y);
                        ctx.lineTo(target.x, target.y);
                        ctx.stroke();
                    }
                });
            });

            animationFrameId = requestAnimationFrame(animate);
        }

        // 事件监听
        function initEvents() {
            let resizeTimer;
            window.addEventListener('resize', () => {
                clearTimeout(resizeTimer);
                resizeTimer = setTimeout(() => {
                    updateSize();
                    createParticles();
                }, 200);
            });

            window.addEventListener('mousemove', e => {
                mouse.x = e.clientX;
                mouse.y = e.clientY;
            });

            window.addEventListener('mouseout', () => {
                mouse.x = null;
                mouse.y = null;
            });
        }

        // 初始化入口
        function init() {
            initCanvas();
            createParticles();
            initEvents();
            animate();
        }

        // 清理函数
        function cleanup() {
            cancelAnimationFrame(animationFrameId);
            canvas.remove();
        }

        return { init, cleanup };
    })();

    // 执行初始化
    if (document.readyState === 'complete') {
        GLOBAL_PARTICLE_EFFECT.init();
    } else {
        window.addEventListener('load', GLOBAL_PARTICLE_EFFECT.init);
    }

    // 页面卸载时清理
    window.addEventListener('beforeunload', GLOBAL_PARTICLE_EFFECT.cleanup);
}